<?php
class login extends base{

	public function init(){
		parent::init();

		$this->adminObj = D('company_admin');
		$this->userObj = D('sys_user');
		$this->weixinObj = D('weixin');
		$this->config = $this->setting['wxapp'];
	}

	public function index()
	{
		$formData = $this->formData('formData');
		if($formData){

			$username = $formData['username'];
			$password = $formData['password'];
			
	        $admin = $this->adminObj->check_login($username,$password);
	        if($admin){
	            $this->adminObj->up_time($admin['id']);
				$data['admin_id'] = $admin['admin']['id'];
				$data['admin_token'] = $admin['token'];
	        	$this->renderSuccess('登录成功','',$data);

	        }else{
	            $this->renderError('登录失败');
	        }

		}
	}

	public function applogin()
    {
		$formData = $this->formData('formData');
		if($formData){
			// dump($formData['username']);exit;
			$admin = $this->adminObj->check_login($formData['username'],$formData['password']);
			if($admin){
				$data['admin_id'] = $admin['admin']['id'];
				$data['admin_token'] = $admin['token'];
				$this->renderSuccess('登录成功','',$data);
			}
		}
		
		$this->renderError('登录失败');
    }

	public function wxlogin()
    {

		$userinfo = $this->formData('formData');
		$user = $this->userObj->up_userinfo($this->user['id'],$userinfo);
		$this->renderSuccess('登录成功','',$user);
    }

	public function wxtel()
    {
		$code = arg('code');
		$iv = arg('iv');
		$encryptedData = arg('encrypted_data');

		if($code && $iv && $encryptedData){
			$tel = $this->weixinObj->getUserTel($this->config,$code,$iv,$encryptedData);
			// dump($tel);exit;
			if($tel){
				$res = $this->userObj->tel_login($tel);
				$this->renderSuccess('登录成功','',$res);
			}
		}
    }

	// 退出
	public function logout(){
		// 这里是PHP.net关于删除SESSION的方法
		$_SESSION = array();
		if (isset($_COOKIE[session_name()])) {setcookie(session_name(), '', time()-42000, '/');}
		session_destroy();

		$data['token'] = '';
		$this->renderSuccess('退出成功','',$data);
	}

}